正则表达式匹配字符串值并替换 golang 中的所有匹配项

您所在的位置:网站首页 url 允许的字符 正则表达式匹配字符串值并替换 golang 中的所有匹配项

正则表达式匹配字符串值并替换 golang 中的所有匹配项

2023-03-30 19:54| 来源: 网络整理| 查看: 265

({{(media|skin) url=\\"(.*)\\"}})应该做的工作。

它还将允许您在代码中将类型(媒体或皮肤)作为字符串获取,以便在需要时进一步使用。

例如,这段代码:

package main

import "fmt"

import "regexp"

func main() {

    re := regexp.MustCompile(`{{(media|skin) url=.*}}`)

    stringMedia := "{{media url=\"wysiwyg/Out_story.png\"}}"

    stringSkin := "{{skin url=\"wysiwyg/Out_story.png\"}}"

    match := re.FindStringSubmatch(stringMedia)

    if len(match) != 0 {

        fmt.Printf("1. %s\n", match[1])

    }

    match = re.FindStringSubmatch(stringSkin)

    if len(match) != 0 {

        fmt.Printf("2. %s\n", match[1])

    }

}

产出

1. media

2. skin

然后,要用它包含的 URL 替换匹配项,您可以这样做(注意对 regexp 的调整以独立捕获完整匹配项和 url):

package main

import (

    "fmt"

    "regexp"

    "strings"

)

func main() {

    re := regexp.MustCompile(`({{(media|skin) url=\\"(.*)\\"}})`)

    stringMedia := "other stuff {{media url=\"wysiwyg/Out_story.png\"}} other stuff"

    stringSkin := "other stuff {{skin url=\"wysiwyg/Out_story.png\"}} other stuff"

    match := re.FindStringSubmatch(stringMedia)

    if len(match) != 0 {

        stringMedia = strings.Replace(stringMedia, match[1], fmt.Sprintf("https://img.abc.com/xyz/%s", match[3]), -1)

        fmt.Println(stringMedia)

    }

    match = re.FindStringSubmatch(stringSkin)

    if len(match) != 0 {

        stringSkin = strings.Replace(stringSkin, match[1], fmt.Sprintf("https://img.abc.com/xyz/%s", match[3]), -1)

        fmt.Println(stringSkin)

    }

}

输出:

other stuff https://img.abc.com/xyz/wysiwyg/Out_story.png other stuff

other stuff https://img.abc.com/xyz/wysiwyg/Out_story.png other stuff

您可以在regex-golang.appspot.com或playground上自行测试。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3